wheel.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. """Support for installing and building the "wheel" binary package format.
  2. """
  3. from __future__ import absolute_import
  4. import collections
  5. import compileall
  6. import contextlib
  7. import csv
  8. import importlib
  9. import logging
  10. import os.path
  11. import re
  12. import shutil
  13. import sys
  14. import warnings
  15. from base64 import urlsafe_b64encode
  16. from itertools import chain, starmap
  17. from zipfile import ZipFile
  18. from pip._vendor import pkg_resources
  19. from pip._vendor.distlib.scripts import ScriptMaker
  20. from pip._vendor.distlib.util import get_export_entry
  21. from pip._vendor.six import (
  22. PY2,
  23. ensure_str,
  24. ensure_text,
  25. itervalues,
  26. reraise,
  27. text_type,
  28. )
  29. from pip._vendor.six.moves import filterfalse, map
  30. from pip._internal.exceptions import InstallationError
  31. from pip._internal.locations import get_major_minor_version
  32. from pip._internal.models.direct_url import DIRECT_URL_METADATA_NAME, DirectUrl
  33. from pip._internal.models.scheme import SCHEME_KEYS
  34. from pip._internal.utils.filesystem import adjacent_tmp_file, replace
  35. from pip._internal.utils.misc import (
  36. captured_stdout,
  37. ensure_dir,
  38. hash_file,
  39. partition,
  40. )
  41. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  42. from pip._internal.utils.unpacking import (
  43. current_umask,
  44. is_within_directory,
  45. set_extracted_file_to_default_mode_plus_executable,
  46. zip_item_is_executable,
  47. )
  48. from pip._internal.utils.wheel import (
  49. parse_wheel,
  50. pkg_resources_distribution_for_wheel,
  51. )
  52. # Use the custom cast function at runtime to make cast work,
  53. # and import typing.cast when performing pre-commit and type
  54. # checks
  55. if not MYPY_CHECK_RUNNING:
  56. from pip._internal.utils.typing import cast
  57. else:
  58. from email.message import Message
  59. from typing import (
  60. Any,
  61. Callable,
  62. Dict,
  63. IO,
  64. Iterable,
  65. Iterator,
  66. List,
  67. NewType,
  68. Optional,
  69. Protocol,
  70. Sequence,
  71. Set,
  72. Tuple,
  73. Union,
  74. cast,
  75. )
  76. from zipfile import ZipInfo
  77. from pip._vendor.pkg_resources import Distribution
  78. from pip._internal.models.scheme import Scheme
  79. from pip._internal.utils.filesystem import NamedTemporaryFileResult
  80. RecordPath = NewType('RecordPath', text_type)
  81. InstalledCSVRow = Tuple[RecordPath, str, Union[int, str]]
  82. class File(Protocol):
  83. src_record_path = None # type: RecordPath
  84. dest_path = None # type: text_type
  85. changed = None # type: bool
  86. def save(self):
  87. # type: () -> None
  88. pass
  89. logger = logging.getLogger(__name__)
  90. def rehash(path, blocksize=1 << 20):
  91. # type: (text_type, int) -> Tuple[str, str]
  92. """Return (encoded_digest, length) for path using hashlib.sha256()"""
  93. h, length = hash_file(path, blocksize)
  94. digest = 'sha256=' + urlsafe_b64encode(
  95. h.digest()
  96. ).decode('latin1').rstrip('=')
  97. # unicode/str python2 issues
  98. return (digest, str(length)) # type: ignore
  99. def csv_io_kwargs(mode):
  100. # type: (str) -> Dict[str, Any]
  101. """Return keyword arguments to properly open a CSV file
  102. in the given mode.
  103. """
  104. if PY2:
  105. return {'mode': '{}b'.format(mode)}
  106. else:
  107. return {'mode': mode, 'newline': '', 'encoding': 'utf-8'}
  108. def fix_script(path):
  109. # type: (text_type) -> bool
  110. """Replace #!python with #!/path/to/python
  111. Return True if file was changed.
  112. """
  113. # XXX RECORD hashes will need to be updated
  114. assert os.path.isfile(path)
  115. with open(path, 'rb') as script:
  116. firstline = script.readline()
  117. if not firstline.startswith(b'#!python'):
  118. return False
  119. exename = sys.executable.encode(sys.getfilesystemencoding())
  120. firstline = b'#!' + exename + os.linesep.encode("ascii")
  121. rest = script.read()
  122. with open(path, 'wb') as script:
  123. script.write(firstline)
  124. script.write(rest)
  125. return True
  126. def wheel_root_is_purelib(metadata):
  127. # type: (Message) -> bool
  128. return metadata.get("Root-Is-Purelib", "").lower() == "true"
  129. def get_entrypoints(distribution):
  130. # type: (Distribution) -> Tuple[Dict[str, str], Dict[str, str]]
  131. # get the entry points and then the script names
  132. try:
  133. console = distribution.get_entry_map('console_scripts')
  134. gui = distribution.get_entry_map('gui_scripts')
  135. except KeyError:
  136. # Our dict-based Distribution raises KeyError if entry_points.txt
  137. # doesn't exist.
  138. return {}, {}
  139. def _split_ep(s):
  140. # type: (pkg_resources.EntryPoint) -> Tuple[str, str]
  141. """get the string representation of EntryPoint,
  142. remove space and split on '='
  143. """
  144. split_parts = str(s).replace(" ", "").split("=")
  145. return split_parts[0], split_parts[1]
  146. # convert the EntryPoint objects into strings with module:function
  147. console = dict(_split_ep(v) for v in console.values())
  148. gui = dict(_split_ep(v) for v in gui.values())
  149. return console, gui
  150. def message_about_scripts_not_on_PATH(scripts):
  151. # type: (Sequence[str]) -> Optional[str]
  152. """Determine if any scripts are not on PATH and format a warning.
  153. Returns a warning message if one or more scripts are not on PATH,
  154. otherwise None.
  155. """
  156. if not scripts:
  157. return None
  158. # Group scripts by the path they were installed in
  159. grouped_by_dir = collections.defaultdict(set) # type: Dict[str, Set[str]]
  160. for destfile in scripts:
  161. parent_dir = os.path.dirname(destfile)
  162. script_name = os.path.basename(destfile)
  163. grouped_by_dir[parent_dir].add(script_name)
  164. # We don't want to warn for directories that are on PATH.
  165. not_warn_dirs = [
  166. os.path.normcase(i).rstrip(os.sep) for i in
  167. os.environ.get("PATH", "").split(os.pathsep)
  168. ]
  169. # If an executable sits with sys.executable, we don't warn for it.
  170. # This covers the case of venv invocations without activating the venv.
  171. not_warn_dirs.append(os.path.normcase(os.path.dirname(sys.executable)))
  172. warn_for = {
  173. parent_dir: scripts for parent_dir, scripts in grouped_by_dir.items()
  174. if os.path.normcase(parent_dir) not in not_warn_dirs
  175. } # type: Dict[str, Set[str]]
  176. if not warn_for:
  177. return None
  178. # Format a message
  179. msg_lines = []
  180. for parent_dir, dir_scripts in warn_for.items():
  181. sorted_scripts = sorted(dir_scripts) # type: List[str]
  182. if len(sorted_scripts) == 1:
  183. start_text = "script {} is".format(sorted_scripts[0])
  184. else:
  185. start_text = "scripts {} are".format(
  186. ", ".join(sorted_scripts[:-1]) + " and " + sorted_scripts[-1]
  187. )
  188. msg_lines.append(
  189. "The {} installed in '{}' which is not on PATH."
  190. .format(start_text, parent_dir)
  191. )
  192. last_line_fmt = (
  193. "Consider adding {} to PATH or, if you prefer "
  194. "to suppress this warning, use --no-warn-script-location."
  195. )
  196. if len(msg_lines) == 1:
  197. msg_lines.append(last_line_fmt.format("this directory"))
  198. else:
  199. msg_lines.append(last_line_fmt.format("these directories"))
  200. # Add a note if any directory starts with ~
  201. warn_for_tilde = any(
  202. i[0] == "~" for i in os.environ.get("PATH", "").split(os.pathsep) if i
  203. )
  204. if warn_for_tilde:
  205. tilde_warning_msg = (
  206. "NOTE: The current PATH contains path(s) starting with `~`, "
  207. "which may not be expanded by all applications."
  208. )
  209. msg_lines.append(tilde_warning_msg)
  210. # Returns the formatted multiline message
  211. return "\n".join(msg_lines)
  212. def _normalized_outrows(outrows):
  213. # type: (Iterable[InstalledCSVRow]) -> List[Tuple[str, str, str]]
  214. """Normalize the given rows of a RECORD file.
  215. Items in each row are converted into str. Rows are then sorted to make
  216. the value more predictable for tests.
  217. Each row is a 3-tuple (path, hash, size) and corresponds to a record of
  218. a RECORD file (see PEP 376 and PEP 427 for details). For the rows
  219. passed to this function, the size can be an integer as an int or string,
  220. or the empty string.
  221. """
  222. # Normally, there should only be one row per path, in which case the
  223. # second and third elements don't come into play when sorting.
  224. # However, in cases in the wild where a path might happen to occur twice,
  225. # we don't want the sort operation to trigger an error (but still want
  226. # determinism). Since the third element can be an int or string, we
  227. # coerce each element to a string to avoid a TypeError in this case.
  228. # For additional background, see--
  229. # https://github.com/pypa/pip/issues/5868
  230. return sorted(
  231. (ensure_str(record_path, encoding='utf-8'), hash_, str(size))
  232. for record_path, hash_, size in outrows
  233. )
  234. def _record_to_fs_path(record_path):
  235. # type: (RecordPath) -> text_type
  236. return record_path
  237. def _fs_to_record_path(path, relative_to=None):
  238. # type: (text_type, Optional[text_type]) -> RecordPath
  239. if relative_to is not None:
  240. # On Windows, do not handle relative paths if they belong to different
  241. # logical disks
  242. if os.path.splitdrive(path)[0].lower() == \
  243. os.path.splitdrive(relative_to)[0].lower():
  244. path = os.path.relpath(path, relative_to)
  245. path = path.replace(os.path.sep, '/')
  246. return cast('RecordPath', path)
  247. def _parse_record_path(record_column):
  248. # type: (str) -> RecordPath
  249. p = ensure_text(record_column, encoding='utf-8')
  250. return cast('RecordPath', p)
  251. def get_csv_rows_for_installed(
  252. old_csv_rows, # type: List[List[str]]
  253. installed, # type: Dict[RecordPath, RecordPath]
  254. changed, # type: Set[RecordPath]
  255. generated, # type: List[str]
  256. lib_dir, # type: str
  257. ):
  258. # type: (...) -> List[InstalledCSVRow]
  259. """
  260. :param installed: A map from archive RECORD path to installation RECORD
  261. path.
  262. """
  263. installed_rows = [] # type: List[InstalledCSVRow]
  264. for row in old_csv_rows:
  265. if len(row) > 3:
  266. logger.warning('RECORD line has more than three elements: %s', row)
  267. old_record_path = _parse_record_path(row[0])
  268. new_record_path = installed.pop(old_record_path, old_record_path)
  269. if new_record_path in changed:
  270. digest, length = rehash(_record_to_fs_path(new_record_path))
  271. else:
  272. digest = row[1] if len(row) > 1 else ''
  273. length = row[2] if len(row) > 2 else ''
  274. installed_rows.append((new_record_path, digest, length))
  275. for f in generated:
  276. path = _fs_to_record_path(f, lib_dir)
  277. digest, length = rehash(f)
  278. installed_rows.append((path, digest, length))
  279. for installed_record_path in itervalues(installed):
  280. installed_rows.append((installed_record_path, '', ''))
  281. return installed_rows
  282. def get_console_script_specs(console):
  283. # type: (Dict[str, str]) -> List[str]
  284. """
  285. Given the mapping from entrypoint name to callable, return the relevant
  286. console script specs.
  287. """
  288. # Don't mutate caller's version
  289. console = console.copy()
  290. scripts_to_generate = []
  291. # Special case pip and setuptools to generate versioned wrappers
  292. #
  293. # The issue is that some projects (specifically, pip and setuptools) use
  294. # code in setup.py to create "versioned" entry points - pip2.7 on Python
  295. # 2.7, pip3.3 on Python 3.3, etc. But these entry points are baked into
  296. # the wheel metadata at build time, and so if the wheel is installed with
  297. # a *different* version of Python the entry points will be wrong. The
  298. # correct fix for this is to enhance the metadata to be able to describe
  299. # such versioned entry points, but that won't happen till Metadata 2.0 is
  300. # available.
  301. # In the meantime, projects using versioned entry points will either have
  302. # incorrect versioned entry points, or they will not be able to distribute
  303. # "universal" wheels (i.e., they will need a wheel per Python version).
  304. #
  305. # Because setuptools and pip are bundled with _ensurepip and virtualenv,
  306. # we need to use universal wheels. So, as a stopgap until Metadata 2.0, we
  307. # override the versioned entry points in the wheel and generate the
  308. # correct ones. This code is purely a short-term measure until Metadata 2.0
  309. # is available.
  310. #
  311. # To add the level of hack in this section of code, in order to support
  312. # ensurepip this code will look for an ``ENSUREPIP_OPTIONS`` environment
  313. # variable which will control which version scripts get installed.
  314. #
  315. # ENSUREPIP_OPTIONS=altinstall
  316. # - Only pipX.Y and easy_install-X.Y will be generated and installed
  317. # ENSUREPIP_OPTIONS=install
  318. # - pipX.Y, pipX, easy_install-X.Y will be generated and installed. Note
  319. # that this option is technically if ENSUREPIP_OPTIONS is set and is
  320. # not altinstall
  321. # DEFAULT
  322. # - The default behavior is to install pip, pipX, pipX.Y, easy_install
  323. # and easy_install-X.Y.
  324. pip_script = console.pop('pip', None)
  325. if pip_script:
  326. if "ENSUREPIP_OPTIONS" not in os.environ:
  327. scripts_to_generate.append('pip = ' + pip_script)
  328. if os.environ.get("ENSUREPIP_OPTIONS", "") != "altinstall":
  329. scripts_to_generate.append(
  330. 'pip{} = {}'.format(sys.version_info[0], pip_script)
  331. )
  332. scripts_to_generate.append(
  333. 'pip{} = {}'.format(get_major_minor_version(), pip_script)
  334. )
  335. # Delete any other versioned pip entry points
  336. pip_ep = [k for k in console if re.match(r'pip(\d(\.\d)?)?$', k)]
  337. for k in pip_ep:
  338. del console[k]
  339. easy_install_script = console.pop('easy_install', None)
  340. if easy_install_script:
  341. if "ENSUREPIP_OPTIONS" not in os.environ:
  342. scripts_to_generate.append(
  343. 'easy_install = ' + easy_install_script
  344. )
  345. scripts_to_generate.append(
  346. 'easy_install-{} = {}'.format(
  347. get_major_minor_version(), easy_install_script
  348. )
  349. )
  350. # Delete any other versioned easy_install entry points
  351. easy_install_ep = [
  352. k for k in console if re.match(r'easy_install(-\d\.\d)?$', k)
  353. ]
  354. for k in easy_install_ep:
  355. del console[k]
  356. # Generate the console entry points specified in the wheel
  357. scripts_to_generate.extend(starmap('{} = {}'.format, console.items()))
  358. return scripts_to_generate
  359. class ZipBackedFile(object):
  360. def __init__(self, src_record_path, dest_path, zip_file):
  361. # type: (RecordPath, text_type, ZipFile) -> None
  362. self.src_record_path = src_record_path
  363. self.dest_path = dest_path
  364. self._zip_file = zip_file
  365. self.changed = False
  366. def _getinfo(self):
  367. # type: () -> ZipInfo
  368. if not PY2:
  369. return self._zip_file.getinfo(self.src_record_path)
  370. # Python 2 does not expose a way to detect a ZIP's encoding, but the
  371. # wheel specification (PEP 427) explicitly mandates that paths should
  372. # use UTF-8, so we assume it is true.
  373. return self._zip_file.getinfo(self.src_record_path.encode("utf-8"))
  374. def save(self):
  375. # type: () -> None
  376. # directory creation is lazy and after file filtering
  377. # to ensure we don't install empty dirs; empty dirs can't be
  378. # uninstalled.
  379. parent_dir = os.path.dirname(self.dest_path)
  380. ensure_dir(parent_dir)
  381. # When we open the output file below, any existing file is truncated
  382. # before we start writing the new contents. This is fine in most
  383. # cases, but can cause a segfault if pip has loaded a shared
  384. # object (e.g. from pyopenssl through its vendored urllib3)
  385. # Since the shared object is mmap'd an attempt to call a
  386. # symbol in it will then cause a segfault. Unlinking the file
  387. # allows writing of new contents while allowing the process to
  388. # continue to use the old copy.
  389. if os.path.exists(self.dest_path):
  390. os.unlink(self.dest_path)
  391. zipinfo = self._getinfo()
  392. with self._zip_file.open(zipinfo) as f:
  393. with open(self.dest_path, "wb") as dest:
  394. shutil.copyfileobj(f, dest)
  395. if zip_item_is_executable(zipinfo):
  396. set_extracted_file_to_default_mode_plus_executable(self.dest_path)
  397. class ScriptFile(object):
  398. def __init__(self, file):
  399. # type: (File) -> None
  400. self._file = file
  401. self.src_record_path = self._file.src_record_path
  402. self.dest_path = self._file.dest_path
  403. self.changed = False
  404. def save(self):
  405. # type: () -> None
  406. self._file.save()
  407. self.changed = fix_script(self.dest_path)
  408. class MissingCallableSuffix(InstallationError):
  409. def __init__(self, entry_point):
  410. # type: (str) -> None
  411. super(MissingCallableSuffix, self).__init__(
  412. "Invalid script entry point: {} - A callable "
  413. "suffix is required. Cf https://packaging.python.org/"
  414. "specifications/entry-points/#use-for-scripts for more "
  415. "information.".format(entry_point)
  416. )
  417. def _raise_for_invalid_entrypoint(specification):
  418. # type: (str) -> None
  419. entry = get_export_entry(specification)
  420. if entry is not None and entry.suffix is None:
  421. raise MissingCallableSuffix(str(entry))
  422. class PipScriptMaker(ScriptMaker):
  423. def make(self, specification, options=None):
  424. # type: (str, Dict[str, Any]) -> List[str]
  425. _raise_for_invalid_entrypoint(specification)
  426. return super(PipScriptMaker, self).make(specification, options)
  427. def _install_wheel(
  428. name, # type: str
  429. wheel_zip, # type: ZipFile
  430. wheel_path, # type: str
  431. scheme, # type: Scheme
  432. pycompile=True, # type: bool
  433. warn_script_location=True, # type: bool
  434. direct_url=None, # type: Optional[DirectUrl]
  435. requested=False, # type: bool
  436. ):
  437. # type: (...) -> None
  438. """Install a wheel.
  439. :param name: Name of the project to install
  440. :param wheel_zip: open ZipFile for wheel being installed
  441. :param scheme: Distutils scheme dictating the install directories
  442. :param req_description: String used in place of the requirement, for
  443. logging
  444. :param pycompile: Whether to byte-compile installed Python files
  445. :param warn_script_location: Whether to check that scripts are installed
  446. into a directory on PATH
  447. :raises UnsupportedWheel:
  448. * when the directory holds an unpacked wheel with incompatible
  449. Wheel-Version
  450. * when the .dist-info dir does not match the wheel
  451. """
  452. info_dir, metadata = parse_wheel(wheel_zip, name)
  453. if wheel_root_is_purelib(metadata):
  454. lib_dir = scheme.purelib
  455. else:
  456. lib_dir = scheme.platlib
  457. # Record details of the files moved
  458. # installed = files copied from the wheel to the destination
  459. # changed = files changed while installing (scripts #! line typically)
  460. # generated = files newly generated during the install (script wrappers)
  461. installed = {} # type: Dict[RecordPath, RecordPath]
  462. changed = set() # type: Set[RecordPath]
  463. generated = [] # type: List[str]
  464. def record_installed(srcfile, destfile, modified=False):
  465. # type: (RecordPath, text_type, bool) -> None
  466. """Map archive RECORD paths to installation RECORD paths."""
  467. newpath = _fs_to_record_path(destfile, lib_dir)
  468. installed[srcfile] = newpath
  469. if modified:
  470. changed.add(_fs_to_record_path(destfile))
  471. def all_paths():
  472. # type: () -> Iterable[RecordPath]
  473. names = wheel_zip.namelist()
  474. # If a flag is set, names may be unicode in Python 2. We convert to
  475. # text explicitly so these are valid for lookup in RECORD.
  476. decoded_names = map(ensure_text, names)
  477. for name in decoded_names:
  478. yield cast("RecordPath", name)
  479. def is_dir_path(path):
  480. # type: (RecordPath) -> bool
  481. return path.endswith("/")
  482. def assert_no_path_traversal(dest_dir_path, target_path):
  483. # type: (text_type, text_type) -> None
  484. if not is_within_directory(dest_dir_path, target_path):
  485. message = (
  486. "The wheel {!r} has a file {!r} trying to install"
  487. " outside the target directory {!r}"
  488. )
  489. raise InstallationError(
  490. message.format(wheel_path, target_path, dest_dir_path)
  491. )
  492. def root_scheme_file_maker(zip_file, dest):
  493. # type: (ZipFile, text_type) -> Callable[[RecordPath], File]
  494. def make_root_scheme_file(record_path):
  495. # type: (RecordPath) -> File
  496. normed_path = os.path.normpath(record_path)
  497. dest_path = os.path.join(dest, normed_path)
  498. assert_no_path_traversal(dest, dest_path)
  499. return ZipBackedFile(record_path, dest_path, zip_file)
  500. return make_root_scheme_file
  501. def data_scheme_file_maker(zip_file, scheme):
  502. # type: (ZipFile, Scheme) -> Callable[[RecordPath], File]
  503. scheme_paths = {}
  504. for key in SCHEME_KEYS:
  505. encoded_key = ensure_text(key)
  506. scheme_paths[encoded_key] = ensure_text(
  507. getattr(scheme, key), encoding=sys.getfilesystemencoding()
  508. )
  509. def make_data_scheme_file(record_path):
  510. # type: (RecordPath) -> File
  511. normed_path = os.path.normpath(record_path)
  512. try:
  513. _, scheme_key, dest_subpath = normed_path.split(os.path.sep, 2)
  514. except ValueError:
  515. message = (
  516. "Unexpected file in {}: {!r}. .data directory contents"
  517. " should be named like: '<scheme key>/<path>'."
  518. ).format(wheel_path, record_path)
  519. raise InstallationError(message)
  520. try:
  521. scheme_path = scheme_paths[scheme_key]
  522. except KeyError:
  523. valid_scheme_keys = ", ".join(sorted(scheme_paths))
  524. message = (
  525. "Unknown scheme key used in {}: {} (for file {!r}). .data"
  526. " directory contents should be in subdirectories named"
  527. " with a valid scheme key ({})"
  528. ).format(
  529. wheel_path, scheme_key, record_path, valid_scheme_keys
  530. )
  531. raise InstallationError(message)
  532. dest_path = os.path.join(scheme_path, dest_subpath)
  533. assert_no_path_traversal(scheme_path, dest_path)
  534. return ZipBackedFile(record_path, dest_path, zip_file)
  535. return make_data_scheme_file
  536. def is_data_scheme_path(path):
  537. # type: (RecordPath) -> bool
  538. return path.split("/", 1)[0].endswith(".data")
  539. paths = all_paths()
  540. file_paths = filterfalse(is_dir_path, paths)
  541. root_scheme_paths, data_scheme_paths = partition(
  542. is_data_scheme_path, file_paths
  543. )
  544. make_root_scheme_file = root_scheme_file_maker(
  545. wheel_zip,
  546. ensure_text(lib_dir, encoding=sys.getfilesystemencoding()),
  547. )
  548. files = map(make_root_scheme_file, root_scheme_paths)
  549. def is_script_scheme_path(path):
  550. # type: (RecordPath) -> bool
  551. parts = path.split("/", 2)
  552. return (
  553. len(parts) > 2 and
  554. parts[0].endswith(".data") and
  555. parts[1] == "scripts"
  556. )
  557. other_scheme_paths, script_scheme_paths = partition(
  558. is_script_scheme_path, data_scheme_paths
  559. )
  560. make_data_scheme_file = data_scheme_file_maker(wheel_zip, scheme)
  561. other_scheme_files = map(make_data_scheme_file, other_scheme_paths)
  562. files = chain(files, other_scheme_files)
  563. # Get the defined entry points
  564. distribution = pkg_resources_distribution_for_wheel(
  565. wheel_zip, name, wheel_path
  566. )
  567. console, gui = get_entrypoints(distribution)
  568. def is_entrypoint_wrapper(file):
  569. # type: (File) -> bool
  570. # EP, EP.exe and EP-script.py are scripts generated for
  571. # entry point EP by setuptools
  572. path = file.dest_path
  573. name = os.path.basename(path)
  574. if name.lower().endswith('.exe'):
  575. matchname = name[:-4]
  576. elif name.lower().endswith('-script.py'):
  577. matchname = name[:-10]
  578. elif name.lower().endswith(".pya"):
  579. matchname = name[:-4]
  580. else:
  581. matchname = name
  582. # Ignore setuptools-generated scripts
  583. return (matchname in console or matchname in gui)
  584. script_scheme_files = map(make_data_scheme_file, script_scheme_paths)
  585. script_scheme_files = filterfalse(
  586. is_entrypoint_wrapper, script_scheme_files
  587. )
  588. script_scheme_files = map(ScriptFile, script_scheme_files)
  589. files = chain(files, script_scheme_files)
  590. for file in files:
  591. file.save()
  592. record_installed(file.src_record_path, file.dest_path, file.changed)
  593. def pyc_source_file_paths():
  594. # type: () -> Iterator[text_type]
  595. # We de-duplicate installation paths, since there can be overlap (e.g.
  596. # file in .data maps to same location as file in wheel root).
  597. # Sorting installation paths makes it easier to reproduce and debug
  598. # issues related to permissions on existing files.
  599. for installed_path in sorted(set(installed.values())):
  600. full_installed_path = os.path.join(lib_dir, installed_path)
  601. if not os.path.isfile(full_installed_path):
  602. continue
  603. if not full_installed_path.endswith('.py'):
  604. continue
  605. yield full_installed_path
  606. def pyc_output_path(path):
  607. # type: (text_type) -> text_type
  608. """Return the path the pyc file would have been written to.
  609. """
  610. if PY2:
  611. if sys.flags.optimize:
  612. return path + 'o'
  613. else:
  614. return path + 'c'
  615. else:
  616. return importlib.util.cache_from_source(path)
  617. # Compile all of the pyc files for the installed files
  618. if pycompile:
  619. with captured_stdout() as stdout:
  620. with warnings.catch_warnings():
  621. warnings.filterwarnings('ignore')
  622. for path in pyc_source_file_paths():
  623. # Python 2's `compileall.compile_file` requires a str in
  624. # error cases, so we must convert to the native type.
  625. path_arg = ensure_str(
  626. path, encoding=sys.getfilesystemencoding()
  627. )
  628. success = compileall.compile_file(
  629. path_arg, force=True, quiet=True
  630. )
  631. if success:
  632. pyc_path = pyc_output_path(path)
  633. assert os.path.exists(pyc_path)
  634. pyc_record_path = cast(
  635. "RecordPath", pyc_path.replace(os.path.sep, "/")
  636. )
  637. record_installed(pyc_record_path, pyc_path)
  638. logger.debug(stdout.getvalue())
  639. maker = PipScriptMaker(None, scheme.scripts)
  640. # Ensure old scripts are overwritten.
  641. # See https://github.com/pypa/pip/issues/1800
  642. maker.clobber = True
  643. # Ensure we don't generate any variants for scripts because this is almost
  644. # never what somebody wants.
  645. # See https://bitbucket.org/pypa/distlib/issue/35/
  646. maker.variants = {''}
  647. # This is required because otherwise distlib creates scripts that are not
  648. # executable.
  649. # See https://bitbucket.org/pypa/distlib/issue/32/
  650. maker.set_mode = True
  651. # Generate the console and GUI entry points specified in the wheel
  652. scripts_to_generate = get_console_script_specs(console)
  653. gui_scripts_to_generate = list(starmap('{} = {}'.format, gui.items()))
  654. generated_console_scripts = maker.make_multiple(scripts_to_generate)
  655. generated.extend(generated_console_scripts)
  656. generated.extend(
  657. maker.make_multiple(gui_scripts_to_generate, {'gui': True})
  658. )
  659. if warn_script_location:
  660. msg = message_about_scripts_not_on_PATH(generated_console_scripts)
  661. if msg is not None:
  662. logger.warning(msg)
  663. generated_file_mode = 0o666 & ~current_umask()
  664. @contextlib.contextmanager
  665. def _generate_file(path, **kwargs):
  666. # type: (str, **Any) -> Iterator[NamedTemporaryFileResult]
  667. with adjacent_tmp_file(path, **kwargs) as f:
  668. yield f
  669. os.chmod(f.name, generated_file_mode)
  670. replace(f.name, path)
  671. dest_info_dir = os.path.join(lib_dir, info_dir)
  672. # Record pip as the installer
  673. installer_path = os.path.join(dest_info_dir, 'INSTALLER')
  674. with _generate_file(installer_path) as installer_file:
  675. installer_file.write(b'pip\n')
  676. generated.append(installer_path)
  677. # Record the PEP 610 direct URL reference
  678. if direct_url is not None:
  679. direct_url_path = os.path.join(dest_info_dir, DIRECT_URL_METADATA_NAME)
  680. with _generate_file(direct_url_path) as direct_url_file:
  681. direct_url_file.write(direct_url.to_json().encode("utf-8"))
  682. generated.append(direct_url_path)
  683. # Record the REQUESTED file
  684. if requested:
  685. requested_path = os.path.join(dest_info_dir, 'REQUESTED')
  686. with open(requested_path, "w"):
  687. pass
  688. generated.append(requested_path)
  689. record_text = distribution.get_metadata('RECORD')
  690. record_rows = list(csv.reader(record_text.splitlines()))
  691. rows = get_csv_rows_for_installed(
  692. record_rows,
  693. installed=installed,
  694. changed=changed,
  695. generated=generated,
  696. lib_dir=lib_dir)
  697. # Record details of all files installed
  698. record_path = os.path.join(dest_info_dir, 'RECORD')
  699. with _generate_file(record_path, **csv_io_kwargs('w')) as record_file:
  700. # The type mypy infers for record_file is different for Python 3
  701. # (typing.IO[Any]) and Python 2 (typing.BinaryIO). We explicitly
  702. # cast to typing.IO[str] as a workaround.
  703. writer = csv.writer(cast('IO[str]', record_file))
  704. writer.writerows(_normalized_outrows(rows))
  705. @contextlib.contextmanager
  706. def req_error_context(req_description):
  707. # type: (str) -> Iterator[None]
  708. try:
  709. yield
  710. except InstallationError as e:
  711. message = "For req: {}. {}".format(req_description, e.args[0])
  712. reraise(
  713. InstallationError, InstallationError(message), sys.exc_info()[2]
  714. )
  715. def install_wheel(
  716. name, # type: str
  717. wheel_path, # type: str
  718. scheme, # type: Scheme
  719. req_description, # type: str
  720. pycompile=True, # type: bool
  721. warn_script_location=True, # type: bool
  722. direct_url=None, # type: Optional[DirectUrl]
  723. requested=False, # type: bool
  724. ):
  725. # type: (...) -> None
  726. with ZipFile(wheel_path, allowZip64=True) as z:
  727. with req_error_context(req_description):
  728. _install_wheel(
  729. name=name,
  730. wheel_zip=z,
  731. wheel_path=wheel_path,
  732. scheme=scheme,
  733. pycompile=pycompile,
  734. warn_script_location=warn_script_location,
  735. direct_url=direct_url,
  736. requested=requested,
  737. )